#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<vector>
#include<string>
#include<queue>
#include<unordered_set>
using namespace std;
int shortestPathAllKeys(vector<string>& grid) {
	int m = grid.size(), n = grid[0].size();
	int dx[4] = { 0,0,1,-1 }, dy[4] = { 1,-1,0,0 };
	int startx, starty;
	unordered_set<char> mutex;
	for (int i = 0; i < m; i++)
	{
		for (int j = 0; j < n; j++)
		{
			if (grid[i][j] == '@')
				startx = i, starty = j;
			else if (grid[i][j] >= 'a' && grid[i][j] <= 'z')
				mutex.insert(grid[i][j]);
		}
	}
	int k = mutex.size();
	vector<vector<vector<bool>>> visited(m, vector<vector<bool>>(n, vector<bool>(1<<k, false)));
	visited[startx][starty][0] = true;
	queue<tuple<int, int, int>> q;
	q.push({ startx,starty,0 });
	int path = 0;
	while (!q.empty())
	{
		int sz = q.size();
		for (int i = 0; i < sz; i++)
		{
			auto [x1, y1, sta] = q.front();
			q.pop();
			for (int z = 0; z < 4; k++)
			{
				int x2 = x1 + dx[k], y2 = y1 + dy[k];
				if (x2 >= 0 && x2 < m && y2 >= 0 && y2 < n
					&& grid[x2][y2]!='#'&& visited[x2][y2][sta] == false)
				{
					int c = grid[x2][y2];
					if (c >= 'A' && c <= 'Z')
					{
						if (((sta >> (c - 'A')) & 1) == 0)
							continue;
					}
					else if (c >= 'a' && c <= 'z')
					{
						int tmp = 1<<(c - 'a');
						sta |= tmp;
						if (sta == (1 << k) - 1)
							return path;
					}
					visited[x2][y2][sta] = true;
					q.push({ x2,y2,sta });
				}
			}
		}
	}
	return -1;
}
int main()
{
	vector<string> grid = { "@.a..", "###.#", "b.A.B" };
	shortestPathAllKeys(grid);
	return 0;
}